package com.penghk.hangzhouhouseprice.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class EncryptUtil {

    /**
     *
     * @param word 明文
     * @param encrtKey 加密密钥
     * @return 加密后的秘文
     */
    public static String encryptByAES(String word , String encrtKey) {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(encrtKey.getBytes());
            keyGenerator.init(128 , random);
            SecretKey secretKey = keyGenerator.generateKey();
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE , new SecretKeySpec(secretKey.getEncoded() , "AES"));
            byte[] enwords = cipher.doFinal(word.getBytes());
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(enwords);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     *
     * @param encryWord 秘文
     * @param encrtKey 密钥
     * @return 解密后的明文
     */
    public static String decryptByAES(String encryWord , String encrtKey) {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(encrtKey.getBytes());
            keyGenerator.init(128 , random);
            SecretKey secretKey = keyGenerator.generateKey();
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(secretKey.getEncoded(), "AES"));
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] deBytes = decoder.decodeBuffer(encryWord);
            byte[] words = cipher.doFinal(deBytes);
            return new String(words);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

}
